<?
require_once("ericdingle/model/BaseProvider.php");
require_once("ericdingle/model/comment/CommentEntity.php");

class CommentProvider extends BaseProvider {
	public static function getInstance() {
		return parent::getInstance(__CLASS__);
	}
	
	// CRUD
	
	public function create($comment) {
		$commentID = $this->dataInterface_->executeNonQuery(sprintf(
			"INSERT INTO Comment (CommentID, PostID, Name, Date, Content) " .
			"VALUES (NULL, %d, '%s', '%s', '%s')",
			$comment->getPostID(),
			$this->dataInterface_->sanitize($comment->getName()),
			$comment->getDate()->toMySQLStr(),
			$this->dataInterface_->sanitize($comment->getContent())
		));
		
		$comment->setCommentID($commentID);
	}
	
	public function read($comment = null, $orderBy = null, $limit = null) {
		if (!$orderBy) $orderBy = "C.CommentID ASC";
		
		$result = $this->dataInterface_->executeQuery(
			"SELECT C.CommentID, C.PostID, C.Name, C.Date, C.Content " .
			"FROM Comment C " .
			($comment ? "WHERE " . $this->getConstraints($comment) . " " : "") .
			"ORDER BY $orderBy"
		);
		
		if (!$result) {
			die($this->dataInterface_->getError());
		}
		
		$comments = array();
		while ($row = $this->dataInterface_->getNextRow($result)) {
			array_push($comments, $this->loadEntity($row));
		}
		
		return $comments;
	}
	
	public function update($comment) {
		die("CommentDataProvider.update() is not implemented.");
	}
	
	public function delete($comment) {
		$this->dataInterface_->executeNonQuery(sprintf(
			"DELETE FROM C " .
			"USING Comment C " .
			"WHERE " . $this->getConstraints($comment)
		));
	}
	
	// Helpers
	
	private function getConstraints($comment) {
		$constraints = array();
		if ($commentID = $comment->getCommentID()) {
			array_push($constraints, sprintf("C.CommentID = %d", $commentID));
		}
		if ($postID = $comment->getPostID()) {
			array_push($constraints, sprintf("C.PostID = %d", $postID));
		}
		return implode(" AND ", $constraints);
	}
	
	private function loadEntity($row) {
		return new CommentEntity(
			$row["CommentID"],
			$row["PostID"],
			$row["Name"],
			PostDate::fromMySQLStr($row["Date"]),
			$row["Content"]
		);
	}
	
	public function readByPostID($postID) {
		$comment = new CommentEntity(null, $postID, null, null, null);
		return $this->read($comment);
	}
	
	public function deleteByCommentID($commentID) {
		$comment = new CommentEntity($commentID, null, null, null, null);
		$this->delete($comment);
	}
}
?>
